<template>
  <div class="page">
    <div class="c-main p20">
      <div class="c-body">
        <el-row type="flex" justify="center">
          <el-col :span="14">
            <el-form
              ref="form"
              :model="pageAjax.data"
              :rules="pageAjax.rules"
              label-width="130px"
            >
              <el-row>
                <el-col :span="18">
                  <el-form-item label="登陆手机号：" prop="phone">
                    <el-input
                      placeholder="请输入登陆手机号"
                      v-model="pageAjax.data.phone"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6"
                  ><el-button type="text" disabled="">
                    @{{
                      $store.state.currentCorporation.accountSuffix
                    }}</el-button
                  ></el-col
                >
              </el-row>

              <el-form-item label="微信号：" prop="wxNo">
                <el-input
                  placeholder="请输入微信号"
                  v-model="pageAjax.data.wxNo"
                ></el-input>
              </el-form-item>
              <el-form-item label="用户姓名：" prop="realName">
                <el-input
                  placeholder="请输入用户姓名"
                  v-model="pageAjax.data.realName"
                ></el-input>
              </el-form-item>
              <el-form-item label="用户昵称：" prop="nickName">
                <el-input
                  placeholder="请输入用户昵称"
                  v-model="pageAjax.data.nickName"
                ></el-input>
              </el-form-item>
              <el-form-item label="性别：">
                <el-radio-group v-model="pageAjax.data.gender" size="medium">
                  <el-radio border :label="1">男</el-radio>
                  <el-radio border :label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="登陆密码：" prop="password">
                <el-input
                  placeholder="请输入登陆密码"
                  type="password"
                  v-model="pageAjax.data.password"
                ></el-input>
              </el-form-item>
              <el-form-item label="确认密码：" prop="confirmPassword">
                <el-input
                  placeholder="请输入确认密码"
                  type="password"
                  v-model="pageAjax.data.confirmPassword"
                ></el-input>
              </el-form-item>
              <el-form-item label="账号状态：">
                <el-radio-group v-model="pageAjax.data.status" size="medium">
                  <el-radio border :label="0">正常</el-radio>
                  <el-radio border :label="1">已禁用</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-tabs
                v-model="alone.currentTabId"
                type="card"
                @tab-click="rChangeTabItem"
              >
                <el-tab-pane
                  :label="item.name"
                  :name="'' + item.corpId"
                  :key="item.corpId"
                  v-for="(item, index) in pageAjax.data.corporationPerms"
                >
                  <el-form-item label="是否有该公司权限">
                    <el-switch
                      v-model="pageAjax.data.corporationPerms[index].hasPerm"
                      active-text="是"
                      inactive-text="否"
                      active-color="#13ce66"
                    >
                    </el-switch>
                  </el-form-item>
                  <template
                    v-if="pageAjax.data.corporationPerms[index].hasPerm"
                  >
                    <el-form-item label="增加所属角色">
                      <el-cascader
                        v-model="pageAjax.data.corporationPerms[index].roleIds"
                        :options="roleSupAjax.data"
                        :props="{
                          multiple: true,
                          label: 'roleName',
                          value: 'id',
                          emitPath: false
                        }"
                        clearable
                      ></el-cascader>
                    </el-form-item>
                    <el-form-item label="增加所属平台">
                      <el-cascader
                        v-model="
                          pageAjax.data.corporationPerms[index].platformIds
                        "
                        :options="platformSupAjax.data"
                        :props="{
                          multiple: true,
                          label: 'name',
                          value: 'id',
                          emitPath: false
                        }"
                        clearable
                        :key="Math.random()"
                      ></el-cascader>
                    </el-form-item>
                    <el-form-item label="增加所属部门">
                      <el-button
                        size="small"
                        type="primary"
                        icon="el-icon-circle-plus-outline"
                        @click="rAddDepartmentItem(index)"
                        >增加所属部门</el-button
                      >
                    </el-form-item>

                    <div
                      class="c-departmentBox"
                      v-if="
                        pageAjax.data.corporationPerms[index].departments.length
                      "
                    >
                      <div
                        class="c-departmentItem"
                        v-for="(item, dIndex) in pageAjax.data.corporationPerms[
                          index
                        ].departments"
                        :key="dIndex"
                      >
                        <el-form-item :label="'部门' + (dIndex + 1)">
                          <el-button
                            size="small"
                            type="danger"
                            icon="el-icon-delete"
                            @click="rDeleteDepartmentItem(index, dIndex)"
                            >删除</el-button
                          >
                        </el-form-item>
                        <el-form-item label="所属部门">
                          <el-cascader
                            v-model="
                              pageAjax.data.corporationPerms[index].departments[
                                dIndex
                              ].departmentId
                            "
                            :options="orgSupAjax.data"
                            :props="{
                              label: 'name',
                              value: 'id',
                              checkStrictly: true,
                              emitPath: false
                            }"
                            clearable
                          ></el-cascader>
                        </el-form-item>
                        <el-form-item label="部门权限">
                          <el-select
                            v-model="
                              pageAjax.data.corporationPerms[index].departments[
                                dIndex
                              ].position
                            "
                            placeholder="请选择该部门权限"
                          >
                            <el-option
                              v-for="authorityItem in alone.authorityLevel"
                              :key="authorityItem.value"
                              :label="authorityItem.name"
                              :value="authorityItem.value"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </div>
                    </div>
                  </template>
                </el-tab-pane>
              </el-tabs>

              <el-form-item>
                <el-button type="primary" @click="rSubmitForm">提交</el-button>
                <el-button @click="rBack">取消</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script>
import { addUser, getCorporationList } from "@/api/authority.js";
// import { getOffspringnTree } from "@/assets/js/util.js";
import _ from "lodash";

export default {
  name: "system_authorityCreateUser",
  data() {
    var validatePassworkAgain = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.pageAjax.data.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      pageAjax: {
        btnDisabled: false,
        btnLoading: false,
        loading: false,
        data: {
          phone: "",
          wxNo: "",
          realName: "",
          nickName: "",
          gender: 1,
          password: "",
          confirmPassword: "",
          corporationPerms: [],
          // departments: [],
          // roleIds: "",
          // platformIds: [],
          status: 0
        },
        rules: {
          phone: [
            { required: true, message: "手机号码不能为空", trigger: "blur" },
            //{ length: 11, message: '手机格式不正确', trigger: 'blur' },
            {
              pattern: /^1[3456789]\d{9}$/,
              message: "手机格式不正确",
              trigger: "blur"
            }
          ],
          wxNo: [
            { required: true, message: "微信号不能为空", trigger: "blur" }
          ],
          realName: [
            { required: true, message: "姓名不能为空", trigger: "blur" }
          ],
          nickName: [
            { required: true, message: "昵称不能为空", trigger: "blur" }
          ],
          password: [
            { required: true, message: "密码不能为空", trigger: "blur" },
            {
              min: 5,
              max: 100,
              message: "密码长度必须在5-100个字符",
              trigger: "blur"
            }
          ],
          confirmPassword: [
            { required: true, message: "确认密码不能为空", trigger: "blur" },
            { validator: validatePassworkAgain }
          ]
        }
      },
      corporationsSupAjax: {
        data: []
      },
      orgSupAjax: {
        loading: false,
        data: [],
        orginData: []
      },
      roleSupAjax: {
        loading: false,
        data: [],
        orginData: []
      },
      platformSupAjax: {
        loading: false,
        data: [],
        orginData: []
      },

      alone: {
        currentTabId: 0,
        authorityLevel: [
          {
            name: "实习",
            value: 1
          },
          {
            name: "专员",
            value: 2
          },
          {
            name: "主管",
            value: 3
          },
          {
            name: "经理",
            value: 4
          },
          {
            name: "总监",
            value: 5
          }
        ]
      }
    };
  },
  computed: {
    "corporationsSupAjax.data": () => {}
  },
  created() {
    let _that = this;
    _that.getCorporationsListData();
    _that.getOrgData();
    _that.getRoleData();
    _that.getPlatformData();
  },
  methods: {
    rChangeTabItem() {},
    rAddDepartmentItem(index) {
      let _that = this;
      _that.pageAjax.data.corporationPerms[index].departments.push({
        departmentId: "",
        position: ""
      });
    },
    getCurrentTabId() {
      this.alone.currentTabId = "" + this.corporationsSupAjax.data[0].id;
    },
    rDeleteDepartmentItem(index, dIndex) {
      this.pageAjax.data.corporationPerms[index].departments.splice(dIndex, 1);
      //this.pageAjax.data.departments.splice(index, 1);
    },
    rSubmitForm() {
      let _that = this;
      let submitData = _that.pageAjax.data;
      if (_that.pageAjax.loading) {
        return;
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!submitData.corporationPerms.length) {
            _that.$message.error("公司权限不能为空");
            return;
          }
          for (
            var i = 0, lenI = submitData.corporationPerms.length;
            i < lenI;
            i++
          ) {
            if (submitData.corporationPerms[i].hasPerm) {
              // 判断角色
              if (
                !submitData.corporationPerms[i].roleIds ||
                !submitData.corporationPerms[i].roleIds.length
              ) {
                _that.$message.error(
                  submitData.corporationPerms[i].name + "的角色不能为空"
                );
                return;
              }
              // 判断平台
              if (
                !submitData.corporationPerms[i].platformIds ||
                !submitData.corporationPerms[i].platformIds.length
              ) {
                _that.$message.error(
                  submitData.corporationPerms[i].name + "的平台不能为空"
                );
                return;
              }
              // 判断部门 start
              if (
                !submitData.corporationPerms[i].departments ||
                !submitData.corporationPerms[i].departments.length
              ) {
                _that.$message.error(
                  submitData.corporationPerms[i].name + "的部门不能为空"
                );
                return;
              }

              for (
                var k = 0,
                  lenK = submitData.corporationPerms[i].departments.length;
                k < lenK;
                k++
              ) {
                if (
                  !submitData.corporationPerms[i].departments[k].departmentId ||
                  !submitData.corporationPerms[i].departments[k].position
                ) {
                  _that.$message.error(
                    submitData.corporationPerms[i].name +
                      "公司的部门" +
                      (k + 1) +
                      "的所属部门和部门权限都不能为空"
                  );
                  return;
                }
              }
              // 判断部门 end
            }
          }

          _that.pageAjax.loading = true;
          addUser(submitData)
            .then(resp => {
              let respData = resp.data || {};
              if (respData.code === _that.STATUS.success[0]) {
                _that.goRefresh(-1);
              } else {
                _that.$message.error(respData.msg || "添加失败");
              }
            })
            .finally(() => {
              _that.pageAjax.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    setPageAjaxCorporationPerms() {
      let _that = this;
      let arr = [];
      _that.corporationsSupAjax.data.forEach(item => {
        arr.push({
          name: item.name,
          corpId: item.id,
          departments: [],
          hasPerm: false,
          platformIds: [],
          roleIds: []
        });
      });

      _that.pageAjax.data.corporationPerms = arr;
    },
    getCorporationsListData() {
      let _that = this;
      getCorporationList({ params: { hierarchy: 0 } }).then(resp => {
        let respData = resp.data;

        if (respData.code === _that.STATUS.success[0]) {
          _that.corporationsSupAjax.data = respData.data;
          _that.getCurrentTabId();
          _that.setPageAjaxCorporationPerms();
        }
      });
    },
    getOrgData() {
      let _that = this;
      _that.$store.dispatch("getDepartmentList").then(() => {
        _that.orgSupAjax.data =
          _that.$store.getters.departmentListOffspringnTreeData;
      });
    },
    getRoleData() {
      let _that = this;
      _that.$store.dispatch("getRoleList").then(() => {
        _that.roleSupAjax.data = _that.$store.state.roleList;
      });
    },
    getPlatformData() {
      let _that = this;
      _that.$store.dispatch("getPlatformList").then(() => {
        // let arr = _.cloneDeep(_that.$store.state.allPlatformList);
        // let allItem;
        // // 去掉全部
        // for (var i = arr.length; i--; ) {
        //   if (arr[i].id == 0) {
        //     allItem = arr.splice(i, 1);
        //     break;
        //   }
        // }
        let arr =
          _.cloneDeep(
            _that.$store.getters.allPlatformListOffspringnTreeData(1)
          ) || [];
        _that.platformSupAjax.data = arr;

        // _that.platformSupAjax.data = getOffspringnTree(arr, 0);

        // if (allItem) {
        //   _that.platformSupAjax.data.unshift(allItem[0]);
        // }
      });
    },
    rBack() {
      this.goRefresh(-1);
    }
  }
};
</script>
<style lang="scss" scoped>
.page {
  .s-search {
    border-bottom: 1px solid #eee;
  }
  .c-main {
    margin-top: 20px;
  }
  .c-pagination {
    margin-top: 20px;
    text-align: center;
  }
  .c-departmentBox {
    padding: 20px;
    margin-bottom: 20px;
    border: 1px solid #eee;
  }
  .c-departmentItem {
    padding: 20px 0;
    border-bottom: 1px solid #eee;
    &:last-child {
      border: none;
    }
  }
}
</style>
